import sys
import os
import logging
import re
import json
from typing import Dict, List, Any, Optional, Tuple

# 添加项目根路径到 sys.path
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))

# 导入 MySQLUtil
from shared.utils.MySQLUtil import MySQLUtil

# 设置日志
logger = logging.getLogger(__name__)

def get_各学历及总体_境内升学人数_及升学率(
    project_id: int,
    questionnaire_ids: List[int],
    product_code: Optional[str] = None,
    project_code: Optional[str] = None,
    region_code: Optional[str] = None
) -> Dict[str, Any]:
    """
    各学历及总体，境内升学人数，及升学率 - 指标计算函数
    
    ## 指标说明
    该指标用于计算各学历层次（本科毕业生、专科毕业生、硕士研究生、博士研究生）及总体中，
    选择境内升学的学生人数及其占总人数的比例（升学率）。
    数据来源于学生客观表，通过毕业去向字段筛选境内升学样本。
    
    ## Args
        project_id (int): 项目ID，用于查询项目配置信息
        questionnaire_ids (List[int]): 问卷ID集合，用于确定数据范围
        product_code (Optional[str]): 产品编码，用于路由到特定计算逻辑
        project_code (Optional[str]): 项目编码，用于路由到特定计算逻辑
        region_code (Optional[str]): 区域编码，用于路由到特定计算逻辑
        
    ## 示例
    ### 输入
    ```json
    {
        "project_id": 5895,
        "questionnaire_ids": [11158, 11159]
    }
    ```
    
    ### 输出
    ```json
    {
        "success": true,
        "message": "ok", 
        "code": 0,
        "result": [
            {
                "education": "本科毕业生",
                "count": 120,
                "ratio": 0.25
            },
            {
                "education": "专科毕业生",
                "count": 80,
                "ratio": 0.15
            },
            {
                "education": "硕士研究生",
                "count": 50,
                "ratio": 0.10
            },
            {
                "education": "博士研究生",
                "count": 30,
                "ratio": 0.05
            },
            {
                "education": "总体",
                "count": 280,
                "ratio": 0.55
            }
        ]
    }
    ```
    """
    logger.info(f"开始计算指标: 各学历及总体，境内升学人数，及升学率, 项目ID: {project_id}")
    
    try:
        db = MySQLUtil()  

        # 1. 查询项目配置信息
        project_sql = """
        SELECT client_code, item_year 
        FROM client_item 
        WHERE id = %s
        """
        project_info = db.fetchone(project_sql, (project_id,))
        if not project_info:
            raise ValueError(f"未找到项目ID={project_id}的配置信息")

        client_code = project_info['client_code']
        item_year = project_info['item_year']
        
        logger.info(f"项目配置: client_code={client_code}, item_year={item_year}")

        # 2. 计算 shard_tb_key
        shard_tb_key = re.sub(r'^[A-Za-z]*0*', '', client_code)
        logger.info(f"计算得到 shard_tb_key: {shard_tb_key}")

        # 3. 定义学历枚举值
        education_levels = ['本科毕业生', '专科毕业生', '硕士研究生', '博士研究生']
        
        # 4. 计算结果数据
        result = []
        total_count = 0
        total_denominator = 0
        
        # 4.1 查询总体数据
        sql_total = f"""
        SELECT 
            COUNT(*) AS count,
            (SELECT COUNT(*) FROM dim_client_target_baseinfo_student_calc_{item_year} 
             WHERE shard_tb_key = %s) AS denominator
        FROM dim_client_target_baseinfo_student_calc_{item_year}
        WHERE shard_tb_key = %s 
        AND grad_dest = '境内升学'
        """
        total_data = db.fetchone(sql_total, (shard_tb_key, shard_tb_key))
        if total_data:
            total_count = total_data['count'] or 0
            total_denominator = total_data['denominator'] or 1
            total_ratio = float(total_count) / float(total_denominator)
            
        # 4.2 查询各学历数据
        for edu in education_levels:
            sql = f"""
            SELECT 
                COUNT(*) AS count,
                (SELECT COUNT(*) FROM dim_client_target_baseinfo_student_calc_{item_year} 
                 WHERE shard_tb_key = %s AND education = %s) AS denominator
            FROM dim_client_target_baseinfo_student_calc_{item_year}
            WHERE shard_tb_key = %s 
            AND education = %s
            AND grad_dest = '境内升学'
            """
            data = db.fetchone(sql, (shard_tb_key, edu, shard_tb_key, edu))
            if data:
                count = data['count'] or 0
                denominator = data['denominator'] or 1
                ratio = float(count) / float(denominator)
                result.append({
                    "education": edu,
                    "count": count,
                    "ratio": round(ratio, 4)
                })
        
        # 4.3 添加总体数据
        result.append({
            "education": "总体",
            "count": total_count,
            "ratio": round(total_ratio, 4)
        })

        logger.info(f"指标 '各学历及总体，境内升学人数，及升学率' 计算成功")
        return {
            "success": True,
            "message": "ok",
            "code": 0,
            "result": result
        }

    except Exception as e:
        logger.error(f"计算指标 '各学历及总体，境内升学人数，及升学率' 时发生错误: {str(e)}", exc_info=True)
        return {
            "success": False,
            "message": f"数据获取失败: 各学历及总体，境内升学人数，及升学率",
            "code": 500,
            "error": str(e)
        }